package hb.watcher.monitor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.mysql.jdbc.Statement;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ChatActivity extends TabActivity{

	
	private String MessageType;
	private int Toonid;
	private String MessagePartner;
	private String ToonName;
	public EditText messageHistory;
	public EditText newMessage;
	
	private String Tag = "";
	
	public List<String> MessagesToSend = new ArrayList<String>();
	public List<String> NewMessages = new ArrayList<String>();
	
	private boolean initComplete = false;
	private String statement;
	private DBConnection dbconn;
	public boolean newrow = false;

	@Override
    public void onCreate(Bundle savedInstanceState) {
		 super.onCreate(savedInstanceState);
		 Bundle extras = getIntent().getExtras();
		
		 MessageType = extras.getString("MessageType");
		 MessagePartner = extras.getString("MessagePartner");
		 Toonid = extras.getInt("Toonid");
		 dbconn = (DBConnection)getIntent().getSerializableExtra("dbConn");
		 ToonName = extras.getString("toonname");
		 
		 LinearLayout l1 = new LinearLayout(this);
		 l1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		 l1.setOrientation(LinearLayout.VERTICAL);
		 
	     LinearLayout l2 = new LinearLayout(this);     
	     l2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 85));
	     l2.setOrientation(LinearLayout.HORIZONTAL);
	        
	     
	     Button btn=new Button(this);
	     btn.setText("Send");
	     btn.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));

	     btn.setOnClickListener(new OnClickListener() {         

			@Override
			public void onClick(View arg0) {
				if(!newMessage.getText().equals(null))
				{
					
					MessagesToSend.add(getInsertStatement(newMessage.getText().toString()));
					NewMessages.add("[" + ToonName + "]: " + newMessage.getText() +  System.getProperty("line.separator"));
					messageHistory.append("[" + ToonName + "]: " + newMessage.getText() +  System.getProperty("line.separator"));
					newMessage.setText("");	
				
				}
			}           
	     });

	     
	     messageHistory = new EditText(this);
	     messageHistory.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.MATCH_PARENT, 15));
		 messageHistory.setGravity(Gravity.TOP);
		 messageHistory.setMovementMethod(new ScrollingMovementMethod());
		 messageHistory.setClickable(false);
		 messageHistory.setFocusable(false);    
		 messageHistory.setTextSize(10);
		 messageHistory.setPadding(5, 0, 5, 5);
		   
		 
		 
	     newMessage = new EditText(this);     
	     newMessage.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 20));
		 newMessage.setGravity(Gravity.TOP);
		 newMessage.setMovementMethod(new ScrollingMovementMethod());
		 newMessage.requestFocus();  
		 newMessage.setImeOptions(6);
		 newMessage.setSingleLine();

	    l1.addView(messageHistory);
	    l2.addView(newMessage);
	    l2.addView(btn);
	    l1.addView(l2);
	    
	   
	   	getTabHost().getTabContentView().addView(l1);
	     
	   	dbconn.Register(this);
	   	

	   	
	  //  Updater upt = new Updater();
	   // upt.execute();
		 
		 
	}
	
	private String getInsertStatement(String message)
    {
    	
    	String Statement = "INSERT INTO `TABMessageToSend` (`nToonId`,`szMessageType`,`szMessagePartner`,`szMessageText`,`dtTime`) VALUES (" + Toonid + ", '" + MessageType + "', \"" + MessagePartner + "\", \"" + message + "\", current_timestamp)";
    	return Statement;
    }
	
	public boolean InitDone()
	{
		return initComplete;
	}
	
	public void setTag(String tag)
	{
		Tag = tag;
	}
	public boolean ToonNameSet()
	{
		if(ToonName.equals(null))
			return false;
		else 
			return true;
	}
	
	public void SetToonName(String toonname)
	{
		ToonName = toonname;
	}
	
	private boolean notiState = false;
	
	public void SetNotificationState(boolean state)
	{
		notiState = state;
	}
	
	public boolean GetNotificationState()
	{
		return notiState;
	}
	
	public String getMessageType()
	{
		return MessageType;
	}
	
	public String getStatement()
	{
		return statement;
	}
	public void Init()
	{
		if(MessageType.equals("WHISPER_MESSAGE") )
			statement = "SELECT `nMsgId`,`szMessageText`, `szMessagePartner` FROM `TABMessageReceive` WHERE `nToonId` = " + Toonid + " AND `szMessageType` = \"" + MessageType + "\" AND `szMessagePartner` = \"" + MessagePartner + "\" ORDER BY `nMsgId`";
		else
			statement = "SELECT `nMsgId`,`szMessageText`, `szMessagePartner` FROM `TABMessageReceive` WHERE `nToonId` = " + Toonid + " AND `szMessageType` = \"" + MessageType + "\" ORDER BY `nMsgId`";
		
		initComplete = true;
		
	}
	
	public boolean running = false;
	Updater upt = new Updater();
	public void Update()
	{
		if(!running)
		{
			Updater upt = new Updater();
			upt.execute();
			running = true;
			newrow = false;
		}
		
			
	}
	public void Update(String szMessagePartner, String szMessageText)
	{
		
		NewMessages.add("[" + szMessagePartner + "]: " + szMessageText + System.getProperty("line.separator"));
		newrow = true;
		//messageHistory.append("[" + szMessagePartner + "]: " + szMessageText + System.getProperty("line.separator"));
	}
	
	public List<String> GetNewMessages()
	{
		
		List<String> temp_MessagesToSend = new ArrayList<String>(MessagesToSend);
		Collections.copy(temp_MessagesToSend, MessagesToSend);
		
		MessagesToSend.clear();
		return temp_MessagesToSend;
	}
  
	public List<String> Posted = new ArrayList<String>();
	List<String> MessageList_temp;
	public class Updater extends AsyncTask<Void, Void,Void>
	{

		
		@Override
		protected Void doInBackground(Void... arg0) {
			MessageList_temp = NewMessages;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				running = false;
			}
			
				return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {

			
			messageHistory.setText("");
		
			for(int i = 0; i < MessageList_temp.size(); i++)
			{
				messageHistory.append(MessageList_temp.get(i));
			}
			
			if(MessageList_temp.size() == 1)
				messageHistory.scrollTo(0, 0);
			
			/*
			
			for(int i = 0; i < MessageList_temp.size(); i++)
			{
				boolean bfound = false;
				
				for(int y = 0; y < Posted.size(); y++)
				{
					if((MessageList_temp.get(i).equals(Posted.get(y))))
							bfound = true;
					
				}
				
				if(!bfound)
					messageHistory.append(MessageList_temp.get(i));
				
			}
			*/
			
			running = false;
		}
		
		
	}


		

}
